<!-- <!DOCTYPE>声明：是指示web浏览器关于页面使用哪个HTML版本进行编写的指令 -->
<!-- <!DOCTYPE>声明：不是HTML标签。HTML5不基于SGML，所以不需要引用DTD -->
<!DOCTYPE html>
<!-- <html>与</html>标签：限定了文档的开始点和结束点 -->
<html lang="zh">
<!-- head标签：定义文档的头部 -->
<head>
    <!-- meta标签：描述性标签，描述网站的一些信息 -->
    <meta charset="UTF-8"/>
    <!-- title标签：网页标题 -->
    <title>订单管理系统</title>
    <!-- meta标签：一般用来做SEO（搜索引擎优化） -->
    <meta name="keywords" content="道璞,订单,订单管理,订单管理系统"/>
    <meta name="description" content="道璞订单管理系统"/>
    <link rel="shortcut icon" type="image/x-icon" href="../image/notebook2.svg"/>
    <link rel="stylesheet" href="../css/style.css">
</head>
<!-- body标签：定义文档的主体 -->
<body>
<!-- 布局标签（结构化语义标签） -->
<!-- header标签：定义文档的页眉（介绍信息） -->
<header></header>
<!-- nav标签：定义导航链接的部分 -->
<nav></nav>
<!-- aside标签：可用作文章的侧栏 -->
<aside></aside>
<!-- main标签：规定文档的主要内容。一个网页只能有一个main标签 -->
<!-- main标签：是网页的特异性部分，不应该包含网页中复用的部分 -->
<main>
    <div class="mainbox">
        <div class="Inputorderbox">
            <div id="title">
                输入订单
            </div>
            <table id="enter_order_table" name="enterOrder" >
                <tr>
                    <td colspan="2" >
                        <label>
                            <input name="account" class="Input" placeholder="旺旺号"/>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" >
                        <label>
                            <input name="orderNumber" class="Input" placeholder="订单号"/>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" >
                        <label>
                            <select name="color" class="Input" >
                                <option value ="黑色">黑色</option>
                                <option value ="香槟色">香槟色</option>
                            </select>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <table id="orderTable">
                            <tr>
                                <td>
                                    <label><input name="wardrobeLength" class="Input" placeholder="衣柜长度（㎝）"
                                                  oninput="onInputBox(this)" onBlur="wardrobeLengthOnBlur(this)"/></label>
                                </td>
                                <td>
                                    <label><input name="baseThickness" class="Input" placeholder="底座厚度（㎝）"
                                                  oninput="onInputBox(this)" onBlur="baseThicknessOnBlur(this)"/></label>
                                </td>
                                <td>
                                    <label><input name="clothesRodLength" class="Input" placeholder="衣杆长度（㎝）"
                                                  oninput="onInputBox(this)" onBlur="clothesRodLengthCheck(this)"/></label>
                                </td>
                                <td>
                                    <label><input name="quantity" class="Input" placeholder="数量"
                                                  oninput="value=value.replace(/[^\d]/g,'')" onBlur="onBlurBox(this)"/></label>
                                </td>
                                <td>
                                    <button class="button-login" hidden>删除</button>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" >
                        <button class="button-login" onclick="addTr()">加一行</button>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" >
                        <button class="button-login" onclick="saveOrder()">确定</button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <!-- 悬浮框结构 -->
    <div class="go-top">
        <textarea rows="10" cols="30"></textarea>
    </div>
</main>
<!-- footer标签：定义文档或节的页脚 -->
<footer></footer>
</body>
<script>
    function wardrobeLengthOnBlur(wardrobeLength) {
        onBlurBox(wardrobeLength);
        const parentTr = wardrobeLength.parentNode.parentNode.parentNode;
        parentTr.cells[1].getElementsByTagName("input")[0].value =
            parentTr.parentNode.rows[0].cells[1].getElementsByTagName("input")[0].value === "" ?
            1.4 : parentTr.parentNode.rows[0].cells[1].getElementsByTagName("input")[0].value;
        baseThicknessOnBlur(parentTr.cells[1].getElementsByTagName("input")[0])
    }
    function baseThicknessOnBlur(baseThickness) {
        onBlurBox(baseThickness);
        const parentTr = baseThickness.parentNode.parentNode.parentNode;
        parentTr.cells[2].getElementsByTagName("input")[0].value =
            subtract(parentTr.cells[0].getElementsByTagName("input")[0].value, baseThickness.value);
        clothesRodLengthCheck(parentTr.cells[2].getElementsByTagName("input")[0]);
    }
    function clothesRodLengthCheck(clothesRodLength) {
        onBlurBox(clothesRodLength);
        if (clothesRodLength.value < 0) {
            clothesRodLength.value = 0;
        }
        if (clothesRodLength.value > 600) {
            alert("衣杆长度过长，请检查！");
            clothesRodLength.value = "";
        }
    }
    function onInputBox(inputBox) {
        inputBox.value = inputBox.value.replace(/[^\d.]/g,'')
            .replace(/^\./g, "")
            .replace(/\.{2,}/g, ".")
            .replace(".","$#$")
            .replace(/\./g,"")
            .replace("$#$",".");
    }
    function onBlurBox(inputBox) {
        if (parseFloat(inputBox.value)) {
            inputBox.value = parseFloat(inputBox.value);
        }
    }
    function addTr() {
        const orderTable = document.getElementById("orderTable");
        const row = orderTable.insertRow();
        row.insertCell().innerHTML = "<label><input name=\"wardrobeLength\" class=\"Input\" placeholder=\"衣柜长度（㎝）\" " +
            "oninput=\"onInputBox(this)\" onBlur=\"wardrobeLengthOnBlur(this)\"/></label>";
        row.insertCell().innerHTML = "<label><input name=\"baseThickness\" class=\"Input\" placeholder=\"底座厚度（㎝）\" " +
            "oninput=\"onInputBox(this)\" onBlur=\"baseThicknessOnBlur(this)\"/></label>";
        row.insertCell().innerHTML = "<label><input name=\"clothesRodLength\" class=\"Input\" placeholder=\"衣杆长度（㎝）\"" +
            "oninput=\"onInputBox(this)\" onBlur=\"clothesRodLengthCheck(this)\"/></label>";
        row.insertCell().innerHTML = "<label><input name=\"quantity\" class=\"Input\" placeholder=\"数量\"" +
            "oninput=\"value=value.replace(/[^\\d]/g,'')\" onBlur=\"onBlurBox(this)\"/></label>";
        row.insertCell().innerHTML = "<button class=\"button-login\" onclick='deleteTr(this)'>删除</button>";
    }
    function deleteTr(deletebtn) {
        const tr = deletebtn.parentNode.parentNode;
        const table = tr.parentNode;
        table.removeChild(tr);
    }
    function saveOrder() {
        const tableRows = document.getElementById("enter_order_table").rows;
        const rowsLenth = tableRows.length;
        const account = tableRows[0].cells[0].getElementsByTagName("input")[0].value;
        const orderNumber = tableRows[1].cells[0].getElementsByTagName("input")[0].value;
        const color = tableRows[2].cells[0].getElementsByTagName("select")[0].value;
        if (account === "" || orderNumber === "" || color === "") {
            alert("表格存在空值！");
            return;
        }
        let totalLength = 0;
        let totalQuantity = 0;
        let jsonText = "[";
        let tipsText = color + "：";
        const orderTableRows = document.getElementById("orderTable").rows;
        for (let i = 0; i < orderTableRows.length; i++) {
            let wardrobeLength = orderTableRows[i].cells[0].getElementsByTagName("input")[0].value;
            let baseThickness = orderTableRows[i].cells[1].getElementsByTagName("input")[0].value;
            let clothesRodLength = parseInt(multiply(orderTableRows[i].cells[2].getElementsByTagName("input")[0].value, 10));
            let quantity = orderTableRows[i].cells[3].getElementsByTagName("input")[0].value;
            if (wardrobeLength === "" || baseThickness === "" || clothesRodLength === "" ||quantity === "") {
                alert("表格第 " + (i + 1) + " 行存在空值！");
                return;
            }
            if (wardrobeLength <= 0 || clothesRodLength <=0 ||quantity <= 0) {
                alert("表格第 " + (i + 1) + " 行存在0值！");
                return;
            }
            totalLength = add(totalLength,
                multiply(orderTableRows[i].cells[2].getElementsByTagName("input")[0].value, quantity));
            totalQuantity = add(totalQuantity, quantity);
            jsonText = jsonText + "{\"clothesRodLength\":\"" + clothesRodLength + "\"," +
                "\"quantity\":\"" + quantity + "\"," +
                "\"account\":\"" + account + "\"," +
                "\"orderNumber\":\"" + orderNumber + "\"," +
                "\"color\":\"" + color + "\"}";
            tipsText = tipsText + divide(clothesRodLength, 10) + "/" + quantity;
            if (i !== orderTableRows.length - 1){
                jsonText = jsonText + ",";
                tipsText = tipsText + "，";
            }
        }
        jsonText = jsonText + "]";
        tipsText = tipsText + "，共" + totalQuantity + "根，共" + getRound(divide(totalLength, 100), 3) +  "米";
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/order/createEnterOrder");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(jsonText);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const result = eval("(" + xhr.response + ")");
                    if (result.code === 200) {
                    // alert("上传成功！\n合计长度：" + getRound(divide(totalLength, 100), 3) + "米\n单价：" + getRound(unitPrice, 3) + "元/米");
                    window.open("tips.html?tipsText=" + tipsText + "&totalLength=" + getRound(divide(totalLength, 100), 3), "提示",
                        "height=270, width=480, top=" + (screen.height / 2 - 135) + ", left=" + (screen.width / 2 - 240) +
                        ",toolbar=0, menubar=0, scrollbars=0, resizable=0, location=0, status=0");
                    window.location.replace('enterOrder.html');
                    } else {
                        alert(result.message);
                    }
                } else {
                    alert("上传失败，请重新上传。");
                }
            }
        }
    }

    /*
    * 判断obj是否为一个整数
    */
    function isInteger(obj) {
        return Math.floor(obj) === obj
    }

    /*
    * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
    * @param floatNum {number} 小数
    * @return {object}
    * {times:100, num: 314}
    */
    function toInteger(floatNum) {
        var ret = {times: 1, num: 0};
        if (isInteger(floatNum)) {
            ret.num = floatNum;
            return ret
        }
        var strfi = floatNum + '';
        var dotPos = strfi.indexOf('.');
        var len = strfi.substr(dotPos + 1).length;
        var times = Math.pow(10, len);
        var intNum = parseInt(floatNum * times + 0.5, 10);
        ret.times = times;
        ret.num = intNum;
        return ret
    }

    /*
    * 核心方法，实现加减乘除运算，确保不丢失精度
    * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
    *
    * @param a {number} 运算数1
    * @param b {number} 运算数2
    * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
    *
    */
    function operation(a, b, op) {
        var o1 = toInteger(a);
        var o2 = toInteger(b);
        var n1 = o1.num;
        var n2 = o2.num;
        var t1 = o1.times;
        var t2 = o2.times;
        var max = t1 > t2 ? t1 : t2;
        var result = null;
        switch (op) {
            case 'add':
                if (t1 === t2) { // 两个小数位数相同
                    result = n1 + n2
                } else if (t1 > t2) { // o1 小数位 大于 o2
                    result = n1 + n2 * (t1 / t2)
                } else { // o1 小数位 小于 o2
                    result = n1 * (t2 / t1) + n2
                }
                return result / max;
            case 'subtract':
                if (t1 === t2) {
                    result = n1 - n2
                } else if (t1 > t2) {
                    result = n1 - n2 * (t1 / t2)
                } else {
                    result = n1 * (t2 / t1) - n2
                }
                return result / max;
            case 'multiply':
                result = (n1 * n2) / (t1 * t2);
                return result;
            case 'divide':
                result = (n1 / n2) * (t2 / t1);
                return result
        }
    }

    // 加减乘除的四个接口
    function add(a, b) {
        return operation(a, b, 'add')
    }

    function subtract(a, b) {
        return operation(a, b, 'subtract')
    }

    function multiply(a, b) {
        return operation(a, b, 'multiply')
    }

    function divide(a, b) {
        return operation(a, b, 'divide')
    }

    //取得整数时，不保留小数位，如，2.999，保留2位小数，返回 3
    //num：待四舍五入数值，len：保留小数位数
    function getRound(num, len) {
        return Math.round(num * Math.pow(10, len)) / Math.pow(10, len);
    }

</script>
<!--<script>-->
<!--    var arry = $("#form1").serializeArray();//序列化表单-->
<!--    var obj = {};//分配内存空间-->
<!--    for (var i = 0; i < arry.length; i++) {//数据类型为"自定义类的字段名=数据"后台会自动对数据进行匹配-->
<!--        obj[arry[i].name] = arry[i].value;-->
<!--    }-->
<!--    $.ajax({-->
<!--        url: "localhost:8001/order/getEnterOrderById",-->
<!--        data: obj,//传递数据-->
<!--        type: "post",-->
<!--        success: function (data) {-->
<!--            alert("success");-->
<!--        }-->
<!--    })-->
<!--</script>-->
</html>